<?php
declare(strict_types=1);
namespace App\Dao;

use App\Model\OilAmountChannel;
use App\Model\OilChannel;

class OilChannelDao
{

    /**
     * 获取列表数据
     * @param array $where
     * @param string[] $columns
     * @param int $pageSize
     * @param null $page
     * @return array
     */
    public function getListPage($where=[], $page=null, $pageSize=15,  $columns=['*']){
        $data = OilChannel::query()->where($where)->orderBy('sort', 'desc')->paginate(intval($pageSize), $columns,'page', $page)->toArray();
        $count = OilChannel::query()->where($where)->count();
        return [
            'list' => @$data['data'],
            'count' => $count
        ];
    }

    /**
     * 查询全部
     * @param string[] $columns
     * @return array
     */
    public function getAll($columns=['*']){
        return OilChannel::query()->where('is_del', 1)->orderBy('sort', 'desc')->get($columns)->toArray();
    }


    /**
     * 新建
     * @param $insertArray
     * @return int
     */
    public function add($insertArray){
        $insertArray['add_time'] = time();
        return OilChannel::query()->insertGetId($insertArray);

    }

    /**
     * 根据id获取信息
     * @param $id
     * @param string[] $columns
     * @param bool $isDel
     * @return array
     */
    public function findById($id, $columns=['*'], $isDel=false){

        if($isDel){
            return OilChannel::query()->where(['id'=>$id,'is_del'=>1])->first($columns);
        }

        return OilChannel::query()->find($id, $columns);
    }

    /**
     * 根据id更新信息
     * @param $id
     * @param $updateArray
     * @return int
     */
    public function updateById($id, $updateArray){
        return OilChannel::query()->where('id',  $id)->update($updateArray);
    }


    /**
     * 查询
     * @param $amountId
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function findChannelByAmountArea($amountId)
    {
        return OilAmountChannel::query()
            ->join('oil_channel', 'oil_amount_channel.channel_id', '=', 'oil_channel.id')
            ->where([
                'oil_amount_channel.amount_id'=>$amountId,
                'oil_amount_channel.status'=>2,
                'oil_channel.status'=>1,
                'oil_channel.is_del'=>1,

            ])->where('oil_channel.start_time', '<', time())->orderBy('oil_channel.sort', 'desc')
            ->first(['oil_channel.*','oil_amount_channel.cost']);
    }

    /**
     * 根据商户号获取渠道信息
     * @param $merchantNo
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function merchantNoByChannelInfo($merchantNo){
        return OilChannel::query()->where(['merchant_no'=>$merchantNo, 'status'=>1, 'is_del'=>1])->where('start_time', '<', time())->first();
    }


}